<template>
  <el-dialog
    :title="dataForm.workshopName + '相关配置'"
    :visible.sync="visible"
    :before-close="close"
    :close-on-click-modal="false"
    width="80%">
      <el-tabs v-model="activeName" @tab-click="handleClick">

        <el-tab-pane label="制药用水" name="first">
          <el-table
          	:data="waterDataList"
          	v-loading="waterDataListLoading"
          	border
            fit
            highlight-current-row
            style="width: 100%">
            <el-table-column
              prop="waterGetId"
              header-align="center"
              align="center"
              label="取样点编号"
              width="200">
            </el-table-column>
            <el-table-column
              prop="waterGetName"
              header-align="center"
              align="center"
              label="取样点名称">
              <template slot-scope="{row}">
                <template v-if="row.waterGetId">
                  <template v-if="row.edit">
                    <el-input v-model="row.waterGetName" size="small">
                      <el-button slot="append" @click="waterEditOk(row)" icon="el-icon-check"></el-button>
                      <el-button slot="append" @click="waterEditNo(row)" icon="el-icon-close"></el-button>
                    </el-input>
                  </template>
                  <span v-else style="cursor: pointer;" @click="row.edit = !row.edit">{{ row.waterGetName }}</span>
                </template>
                <template v-else>
                  <el-input v-model="row.waterGetName" size="small">
                    <el-button slot="append" @click="waterAddOk(row)" icon="el-icon-check"></el-button>
                    <el-button slot="append" @click="waterAddNo(row)" icon="el-icon-close"></el-button>
                  </el-input>
                </template>
              </template>
            </el-table-column>
            <el-table-column
              prop="delete"
              header-align="center"
              align="center"
              label="删除"
              width="110">
              <template v-if="row.waterGetId" slot-scope="{row}">
                <el-button @click="deleteWater(row.waterGetId)" size="mini" type="danger" icon="el-icon-delete" circle></el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button style="margin-top: 10px;" type="primary" @click="addWaterGet()" icon="el-icon-plus" circle></el-button>
        </el-tab-pane>

        <el-tab-pane label="环境监测" name="second">
          <el-table
            :data="envGetLevelList"
            v-loading="envGetLevelListLoading"
            border
            fit
            highlight-current-row
            style="width: 60%;">
            <el-table-column
              prop="envGetLevelName"
              header-align="center"
              align="center"
              label="洁净级别">
            </el-table-column>
            <el-table-column
                header-align="center"
                align="center">
                <template slot="header" slot-scope="scope">
                  <span v-html="envGetObjectRadio.envGetObjectName + '最大允许数（CFU/皿）'"></span>
                </template>
              <el-table-column
                prop="envGetLevelWarning"
                header-align="center"
                align="center"
                label="警戒限">
              </el-table-column>
              <el-table-column
                prop="envGetLevelStandard"
                header-align="center"
                align="center"
                label="标准限">
              </el-table-column>
            </el-table-column>
            <el-table-column
              v-if="envGetLevelList.length == 0 ? false : envGetLevelList[0].resultRemark == null ? false : true"
              prop="resultRemark"
              header-align="center"
              align="center"
              label="结果计算">
              <template slot-scope="{row}">
                <span v-html="row.resultRemark"></span>
              </template>
            </el-table-column>
          </el-table>

          <div style="margin-top: 10px">
            <el-radio-group v-model="envGetObjectRadio" @change="getEnvGetList" size="small">
              <el-radio-button
                v-for="item in envGetObjectList"
                :key="item.envGetObjectId"
                :label="item"
                >{{item.envGetObjectName}}</el-radio-button>
            </el-radio-group>
          </div>

          <div style="margin-top: 10px">
            <el-radio-group v-model="envGetFrequencyRadio" @change="getEnvGetList" size="small">
              <el-radio-button
                v-for="item in envGetFrequencyList"
                :key="item.envGetFrequencyId"
                :label="item"
                >{{item.envGetFrequencyName}}</el-radio-button>
            </el-radio-group>
          </div>

          <div style="margin-top: 10px">
            <el-table
            	:data="envDataList"
            	v-loading="envDataListLoading"
              :span-method="merageCellHandle"
            	border
              fit
              highlight-current-row
              style="width: 100%">
              <el-table-column
                prop="envGetId"
                header-align="center"
                align="center"
                label="取样位置编号"
                width="150">
              </el-table-column>
              <el-table-column
                v-if="!isPersonalHygiene"
                prop="roomName"
                header-align="center"
                align="center"
                label="房间名称"
								width="150">
                <template slot-scope="{row}">
                  <template v-if="row.edit">
                    <el-input :disabled="isPersonalHygiene" ref="roomNameRef" v-model="row.roomName" size="small" />
                  </template>
                  <span v-else style="cursor: pointer" @click="edit(row,'edit','roomNameRef')">{{ row.roomName }}</span>
                </template>
              </el-table-column>
              <el-table-column
                v-if="!isPersonalHygiene"
                prop="roomNum"
                header-align="center"
                align="center"
                label="房间编号"
								width="150">
                <template slot-scope="{row}">
                  <template v-if="row.edit">
                    <el-input ref="roomNumRef" v-model="row.roomNum" size="small" />
                  </template>
                  <span v-else style="cursor: pointer" @click="edit(row,'edit','roomNumRef')">{{ row.roomNum }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="envGetLevelName"
                header-align="center"
                align="center"
                label="洁净级别"
                width="350">
                <template slot-scope="{row}">
                  <template v-if="row.edit">
                    <el-select ref="levelRef" size="small" v-model="row.envGetLevelId" filterable placeholder="请选择">
                      <el-option
                        v-for="item in envGetLevelList"
                        :key="item.envGetLevelId"
                        :label="item.envGetLevelName"
                        :value="item.envGetLevelId">
                      </el-option>
                    </el-select>
                    <el-button size="small" v-if="row.envGetId" @click="envEditOk(row)" icon="el-icon-check"></el-button>
                    <el-button size="small" style="margin-left: 0px;" v-if="row.envGetId" @click="envEditNo(row)" icon="el-icon-close"></el-button>
                  </template>
                  <span v-else style="cursor: pointer" @click="edit(row,'edit','levelRef')">{{ row.envGetLevelName }}</span>
                </template>
            </el-table-column>
              <el-table-column
                prop="getName"
                header-align="center"
                align="center"
                :label="isPersonalHygiene ? '测试项目' : '取样位置'">
                <template slot-scope="{row}">
                  <template v-if="row.getNameEdit">
                    <el-input ref="getNameRef" v-model="row.getName" size="small">
                      <el-button v-if="row.envGetId" slot="append" @click="envGetNameEditOk(row)" icon="el-icon-check"></el-button>
                      <el-button v-if="row.envGetId" slot="append" @click="envGetNameEditNo(row)" icon="el-icon-close"></el-button>
                    </el-input>
                  </template>
                  <span v-else style="cursor: pointer" @click="edit(row,'getNameEdit','getNameRef')">{{ row.getName }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="option"
                header-align="center"
                align="center"
                label="操作"
                width="110">
                <template slot-scope="{row}">
                  <el-button v-if="!row.envGetId" @click="envAddOk(row)" size="mini" type="success" icon="el-icon-check" circle />
                  <el-button v-if="!row.envGetId" @click="envAddNo(row)" size="mini" type="warning" icon="el-icon-close" circle />
                  <el-button v-else @click="deleteEnv(row.envGetId)" size="mini" type="danger" icon="el-icon-delete" circle />
                </template>
              </el-table-column>
            </el-table>
            <el-button style="margin-top: 10px" type="primary" @click="addEnv()" icon="el-icon-plus" circle></el-button>
          </div>
        </el-tab-pane>

      </el-tabs>
    </el-dialog>
</template>

<script>
  import CommonMethod from '@/views/mixin/common'
  import {
    getWaterGetListByWorkshopId,
    saveOrUpdateWaterGet,
    deleteWaterGet,
    getEnvGetListByParams,
    getEnvGetObjectList,
    getEnvGetFrequencyList,
    getEnvGetLevelList,
    updateEnvSomeCol,
    updateEnvGet,
    saveEnvGet,
    deleteEnvGet
  } from "@/api/workshop"
  import {isBlank} from '@/common/js/utils'
  import {CODE_OK} from '@/common/js/config'
  export default {
    mixins: [CommonMethod],
    data () {
      return {
      	visible: false,
        dataForm: '',
        activeName: 'first',
        // 水相关
        waterPageIndex: 1,
        waterPageSize: 999,
        waterTotalPage: 0,
        waterDataList: [],
        waterDataListLoading: false,
        //环境相关
        envGetObjectRadio: '',
        envGetObjectList: [],
        envGetFrequencyRadio: '',
        envGetFrequencyList: [],
        envGetLevelListLoading: false,
        envGetLevelList: [],
        envDataList: [],
        envDataListLoading: false,
        //【合并数组】房间名称、房间编号、洁净级别绑定在一起：要么都不合并、要么都合并
        //[2,0,1,3,0,0] 代表第一二行合并,第三行不变,第四五六行合并,0代表原本的那一行被合并,因此这个列被消除8,0,0,0,0,0,0,0,4,0,0,0
        merageArr: [],
        meragePos: 0
      }
    },
    props: ["childDataForm"],
    created() {
    	if (!isBlank(this.childDataForm)) {
    		this.dataForm = this.childDataForm
    	}
      this.getDataList()
    	this.visible = true
    },
    computed: {
      isPersonalHygiene () {
        return this.envGetObjectRadio.envGetObjectName == '个人卫生'
      }
    },
    methods: {
      getDataList() {
        this.getWaterGetList()
        this.getEnvGetInfo()
      },
      handleClick() {

      },
      close() {
        this.$emit('close')
        this.visible = false
      },
      //水相关
      waterAddNo(row) {
        this.waterDataList.splice(this.waterDataList.indexOf(row), 1)
      },
      waterAddOk(row) {
        if (isBlank(row.waterGetName)){
          this.$message.error("请输入取样点名称")
          return
        }
        const data = {
          workshopId: this.dataForm.workshopId,
          waterGetName: row.waterGetName
        }
        saveOrUpdateWaterGet(data).then(res => {
          if (res.code === CODE_OK) {
            this.$message.success('提交成功')
          }else{
            this.$message.error(res.msg)
          }
          this.getWaterGetList()
        })
      },
      addWaterGet() {
        let lastWaterGetId = 0
        if (this.waterDataList.length != 0) {
          lastWaterGetId = this.waterDataList[this.waterDataList.length - 1].waterGetId
        }
        if (lastWaterGetId == undefined) {
          this.$message.error("请先提交上一个取样点")
          return
        }
        let addEntity = {
          waterGetName: '',
          edit: true
        }
        this.waterDataList.push(addEntity)
      },
      deleteWater(id) {
        deleteWaterGet(id).then(res => {
          if (res.code === CODE_OK) {
            this.$message.success('删除成功')
          }else{
            this.$message.error(res.msg)
          }
          this.getWaterGetList()
        })
      },
      waterEditOk(row) {
        if (isBlank(row.waterGetName)){
          this.$message.error("请输入取样点名称")
          return
        }
        saveOrUpdateWaterGet(row).then(res => {
          if (res.code === CODE_OK) {
            this.$message.success('提交成功')
          }else{
            this.$message.error(res.msg)
          }
          this.getWaterGetList()
        })
      },
      waterEditNo(row) {
        row.waterGetName = row.originalWaterGetName
        row.edit = false
      },
      getWaterGetList() {
        this.waterDataListLoading = true
        const params = {
        	page: this.waterPageIndex,
          limit: this.waterPageSize,
          workshopId: this.dataForm.workshopId
        }
        getWaterGetListByWorkshopId(params).then(res => {
        	if (res.code === CODE_OK) {
        		this.waterDataList = res.page.list.map((v,index) => {
              this.$set(v, 'edit', false)
              this.$set(v, 'originalWaterGetName', v.waterGetName)
              return v
            })
        		this.waterTotalPage = res.page.totalCount
        	}else{
        		this.$message.error(res.msg)
        	}
        	this.waterDataListLoading = false
        }).catch()
      },
      //环境相关
      getEnvGetInfo() {
        getEnvGetObjectList().then(res => {
          if (res.code === CODE_OK) {
            this.envGetObjectList = res.envGetObjectList
            this.envGetObjectRadio = this.envGetObjectList[0]
            getEnvGetFrequencyList().then(res => {
              if (res.code === CODE_OK) {
                this.envGetFrequencyList = res.envGetFrequencyList
                this.envGetFrequencyRadio = this.envGetFrequencyList[0]
                this.getEnvGetList()
              }else{
                this.$message.error(res.msg)
              }
            })
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      getEnvGetList() {
        this.envDataListLoading = true
        this.envGetLevelListLoading = true
        getEnvGetLevelList({envGetObjectId: this.envGetObjectRadio.envGetObjectId}).then(res => {
          if (res.code === CODE_OK) {
            this.envGetLevelList = res.envGetLevelList
          }else{
            this.$message.error(res.msg)
          }
          this.envGetLevelListLoading = false
        })
        const params = {
          workshopId: this.dataForm.workshopId,
          envGetObjectId: this.envGetObjectRadio.envGetObjectId,
          envGetFrequencyId: this.envGetFrequencyRadio.envGetFrequencyId
        }
        getEnvGetListByParams(params).then(res => {
          if (res.code === CODE_OK) {
          	this.envDataList = res.envGetList.map((v,index) => {
              this.$set(v, 'edit', false)
              this.$set(v, 'getNameEdit', false)
              this.$set(v, 'originalRoomName', v.roomName)
              this.$set(v, 'originalRoomNum', v.roomNum)
              this.$set(v, 'originalEnvGetLevelId', v.envGetLevelId)
              this.$set(v, 'originalEnvGetLevelName', v.envGetLevelName)
              this.$set(v, 'originalGetName', v.getName)
              return v
            })
            this.merage()
          }else{
          	this.$message.error(res.msg)
          }
          this.envDataListLoading = false
        })
      },
      //初始化merageArr
      merageInit() {
        this.merageArr = []
        this.meragePos = 0
      },
      //生成merageArr
      merage() {
        this.merageInit()
        for (let i=0,j=this.envDataList.length; i<j; i++) {
          if (i == 0) {
            //第一行始终存在
            this.merageArr.push(1)
            this.meragePos = 0
          }else{
            //判断当前元素是否与上一个元素相同，this.meragePos是this.merageArr内容的序号
            if (this.envDataList[i].roomName == this.envDataList[i - 1].roomName) {
              this.merageArr[this.meragePos] += 1
              this.merageArr.push(0)
            }else{
              this.merageArr.push(1)
              this.meragePos = i
            }
          }
        }
      },
      merageCellHandle({ row, column, rowIndex, columnIndex }) {
        // 用rowIndex, columnIndex 找到要合并的开始单元格
        // return {rowspan: 1,colspan: 1 } 表示表格不变
        // return {rowspan: 2,colspan: 1 } 表示表格向下合并一个单元格
        // return {rowspan: 1,colspan: 2 } 表示表格向右合并一个单元格
        // return {rowspan: 0,colspan: 0 } 表示删除此单元格
        if (this.isPersonalHygiene) {
          return {
            rowspan: 1,
            colspan: 1
          }
        }
        //房间名称、房间编号、洁净级别这几列相同数据合并
        if (columnIndex == 1 || columnIndex == 2 || columnIndex == 3) {
          const row = this.merageArr[rowIndex]
          const col = row > 0 ? 1 : 0
          return {
            rowspan: row,
            colspan: col
          }
        }
      },
      envEditOk(row) {
        if (isBlank(row.roomName) ||isBlank(row.roomNum) |isBlank(row.envGetLevelId)){
          this.$message.error("任一项不能为空")
          return
        }
        const data = {
          //在这些条件下修改roomName/roomNum/cleanLevel
          workshopId: this.dataForm.workshopId,
          envGetObjectId: this.envGetObjectRadio.envGetObjectId,
          envGetFrequencyId: this.envGetFrequencyRadio.envGetFrequencyId,
          oldRoomNum: row.originalRoomNum,
          //修改参数
          roomName: row.roomName,
          roomNum: row.roomNum,
          envGetLevelId: row.envGetLevelId
        }
        updateEnvSomeCol(data).then(res => {
          if (res.code === CODE_OK) {
            this.$message.success('提交成功')
          }else{
            this.$message.error(res.msg)
          }
          this.getEnvGetList()
        })
      },
      envEditNo(row) {
        row.roomName = row.originalRoomName
        row.roomNum = row.originalRoomNum
        row.envGetLevelId = row.originalEnvGetLevelId
        row.envGetLevelName = row.originalEnvGetLevelName
        row.edit = false
      },
      envAddOk(row) {
        if (this.isPersonalHygiene) {
          if (isBlank(row.envGetLevelId) || isBlank(row.getName)) {
            this.$message.error("任一项不能为空")
            return
          }
        }else{
          if (isBlank(row.roomName) ||isBlank(row.roomNum) || isBlank(row.envGetLevelId) || isBlank(row.getName)){
            this.$message.error("任一项不能为空")
            return
          }
        }
        const data = {
          //link使用
          workshopId: this.dataForm.workshopId,
          envGetObjectId: this.envGetObjectRadio.envGetObjectId,
          envGetFrequencyId: this.envGetFrequencyRadio.envGetFrequencyId,
          //单表使用
          roomName: row.roomName,
          roomNum: row.roomNum,
          envGetLevelId: row.envGetLevelId,
          getName: row.getName,
          isPersonalHygiene: this.isPersonalHygiene
        }
        saveEnvGet(data).then(res => {
          if (res.code === CODE_OK) {
            this.$message.success('提交成功')
          }else{
            this.$message.error(res.msg)
          }
          this.getEnvGetList()
        })
      },
      envAddNo(row) {
        this.envDataList.splice(this.envDataList.indexOf(row), 1)
      },
      deleteEnv(id) {
        deleteEnvGet(id).then(res => {
          if (res.code === CODE_OK) {
            this.$message.success('删除成功')
          }else{
            this.$message.error(res.msg)
          }
          this.getEnvGetList()
        })
      },
      envGetNameEditOk(row) {
        if (isBlank(row.getName)){
          this.$message.error("请填写取样位置")
          return
        }
        updateEnvGet(row).then(res => {
          if (res.code === CODE_OK) {
            this.$message.success('提交成功')
          }else{
            this.$message.error(res.msg)
          }
          this.getEnvGetList()
        })
      },
      envGetNameEditNo(row) {
        row.getName = row.originalGetName
        row.getNameEdit = !row.getNameEdit
      },
      edit(row,editFlag,refName) {
        row[editFlag] = !row[editFlag]
        this.$nextTick(_ => {
          this.$refs[refName].focus()
        })
      },
      addEnv() {
        let lastEnvGetId = 0
        if (this.envDataList.length != 0) {
          lastEnvGetId = this.envDataList[this.envDataList.length - 1].envGetId
        }
        if (lastEnvGetId == undefined) {
          this.$message.error("请先提交上一个取样配置")
          return
        }
        let addEntity = {
          roomName: '',
          roomNum: '',
          envGetLevelId: '',
          getName: '',
          edit: true,
          getNameEdit: true
        }
        this.merageArr.push(1)
        this.meragePos = 0
        this.envDataList.push(addEntity)
      }
    }
  }
</script>

<style>
</style>
